#include "StdAfx.h"
#include "BlackPonitDetection.h"
#include "pointAbnormality.h"

BlackPonitDetection::BlackPonitDetection(void)
: Detection( )
{
}

BlackPonitDetection::~BlackPonitDetection(void)
{
}

bool BlackPonitDetection::detect( IplImage * src ,  IplImage * marked , vector<Abnormality*>  & abnorm_list ) 
{
	int PointBetween = 0;
	IplImage * dst = cvCloneImage( src ) ;
	CvRect shrunkenROI;
	shrunkenROI.x = src->roi->xOffset + 10;
	shrunkenROI.y = src->roi->yOffset + 10;
	shrunkenROI.height = src->roi->height - 20;
	shrunkenROI.width = src->roi->width - 20;
	cvResetImageROI(dst);
	cvSetImageROI(dst, shrunkenROI);
	cvThreshold( dst,  dst, 32 , 255.0, CV_THRESH_BINARY_INV ) ;
	CvSeq* contours = 0 ;
	CvMemStorage* storage = cvCreateMemStorage(0) ;
	//
	if ( cvFindContours( dst, storage, &contours, sizeof(CvContour),
		CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) ) )
	{
		for( ; contours ; contours = contours->h_next )
		{
			CvRect tempRect = cvBoundingRect( contours , 0 ) ;
			int maxValue = 255;
			CvPoint maxPixel;
			maxPixel.x = 0;
			maxPixel.y = 0;
			for(int i = 0; i < tempRect.height; i++)
			{
				for(int j = 0; j < tempRect.width; j++)
				{
					CvScalar s=cvGet2D( src ,  tempRect.y + i,  tempRect.x +j ); // get the (i,j) pixel value
					if(maxValue > static_cast<int>( s.val[0] ))
					{
						maxValue = static_cast<int>( s.val[0] );
						maxPixel.x = tempRect.x + j;
						maxPixel.y = tempRect.y + i;
					}
				}
			}
			if((tempRect.height +tempRect.width)/2 >= CPublic::point_lim1&&
				(tempRect.height + tempRect.width)/2 < CPublic::point_lim2)
			{
				if(maxValue > 8 && maxValue < 128)
				{
					PointBetween++;
					Abnormality *pa = new PointAbnormality(tempRect, maxPixel);
					abnorm_list.push_back(pa);
				}
			}
		}
	}

	if(PointBetween >= CPublic::darkDotTolerance)
	{
		is_abnormal = true ;
		vector<Abnormality*>::iterator itr = abnorm_list.begin();
		for(;itr != abnorm_list.end(); itr++)
		{
			if((*itr)->rect().height > 1 || (*itr)->rect().width > 1)
			{
				cvCircle( marked , (*itr)->maxValue() , 25 , CV_RGB(255,0,0) , 2 ) ;
			}
		}
	}
	//release
	cvReleaseImage(&dst);
	cvReleaseMemStorage( &storage );
	return !is_abnormal ;
} 